package com.qfedu.hotelssm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.qfedu.hotelssm.dao.ItemsDao;
import com.qfedu.hotelssm.dto.ItemsExportDto;
import com.qfedu.hotelssm.entity.Items;
import com.qfedu.hotelssm.service.intf.ItemsService;
import com.qfedu.hotelssm.util.StringUtil;
import com.qfedu.hotelssm.vo.PageBean;
import com.qfedu.hotelssm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author mk
 * @date 2022/8/28  21:03
 */
@Service
public class ItemsServiceImpl implements ItemsService {
    @Autowired
    private ItemsDao dao;
    @Override
    public R save(Items items) {
        System.out.println(items);
        if(dao.save(items)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if(dao.delete(id)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public PageBean selectPage(String name, int page, int limit) {
        if(StringUtil.isNotEmpty(name)){
            name="%"+name+"%";
        }
        int start=(page-1)*limit;

        return new PageBean((int) dao.selectCount(name),dao.selectPage(name, start, limit));
    }

    @Override
    public R delIds(int[] ids) {
        if (dao.delByIds(ids) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public List<ItemsExportDto> all() {
        return dao.all();
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        if(!file.isEmpty()){
            List<Items> list= EasyExcel.read(file.getInputStream(), Items.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doReadSync();
            if(dao.saveBatch(list)>0 ){
                return  R.ok();
            }
        }
        return R.fail();
    }



}
